﻿Imports HTLibrary
Imports TNCBAL
Imports TNCDAL

Public Class ucDemDet
    Private _objDemDetController As New DemDetController
    Private _objCurrDemDet As tblDemDet

    Public Sub New()
        InitializeComponent()
        TextBoxHelper.TextBox_InitUpperStringEvent(Me.Controls)
        DataGridViewHelper.DataGridView_InitEvent(gridView)
        InitCommands()
    End Sub

    Private Sub ucDemDet_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        BindDataGridView()
        FormatDataGridView()
    End Sub

    Public Sub FormatDataGridView()
        Dim hideColumns As New List(Of String)({"Id_DemDet", "IsActive"})
        Dim renameColumns As New Dictionary(Of String, String)
        renameColumns.Add("DemDetName", "Warehouse")
        CViewer.FormatDataGridView(gridView, hideColumns, renameColumns)
    End Sub

    Public Sub BindDataGridView(ByVal columnName As String, ByVal someText As Integer)
        Dim query As IQueryable(Of tblDemDet) = _objDemDetController.SelectCustom(txtNameSearch.Text)
        Dim source As New BindingSource
        source.DataSource = query
        gridView.DataSource = source
        BindingNavigator1.BindingSource = source

        Dim indexRow As Integer = CViewer.GetIndexRowInDataGridViewByTextSearch(gridView, columnName, someText)
        If indexRow >= 0 Then
            For Each col As DataGridViewColumn In gridView.Columns
                If col.Visible Then
                    gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                    Exit For
                End If
            Next

        End If

        'Nếu không tồn tại row nào
        If gridView.Rows.Count = 0 Then
            ResetControls() 'reset hết các control
        End If
        'disable 2 nút edit và delete nếu row count = 0
        _ucCommands.EnableButtons(False, gridView.Rows.Count)
    End Sub

    Public Sub BindDataGridView(Optional ByVal indexRow As Integer = -1)
        'ResetControls()
        'EnableButtons(False)
        Dim query As IQueryable(Of tblDemDet) = _objDemDetController.SelectCustom(txtNameSearch.Text)
        Dim source As New BindingSource
        source.DataSource = query
        gridView.DataSource = source
        BindingNavigator1.BindingSource = source

        If indexRow > 0 Then
            'Set current row
            'gridViewDemDet.Rows(indexRow).Selected = True
            'gridViewDemDet.FirstDisplayedScrollingRowIndex = indexRow
            For Each col As DataGridViewColumn In gridView.Columns
                If col.Visible Then
                    gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                    Exit For
                End If
            Next
        End If

        'Nếu không tồn tại row nào
        If gridView.Rows.Count = 0 Then
            ResetControls() 'reset hết các control
        End If
        'disable 2 nút edit và delete nếu row count = 0
        _ucCommands.EnableButtons(False, gridView.Rows.Count)
    End Sub


    ' ''' <summary>
    ' ''' Show/hide command buttons
    ' ''' </summary>
    ' ''' <param name="val"></param>
    ' ''' <remarks></remarks>
    'Private Sub EnableButtons(ByVal val As Boolean)
    '    btnUpdate.Enabled = val
    '    btnCancel.Enabled = val

    '    btnAdd.Enabled = Not val
    '    btnEdit.Enabled = Not val
    '    btnDel.Enabled = Not val

    '    txtDemDet.ReadOnly = Not val
    'End Sub

    Public Sub LoadForm()
        'show result
        txtDemDet.Text = _objCurrDemDet.DemDetName
        'chkIsActive.Checked = _objCurrDemDet.IsActive
    End Sub

    Public Sub ResetControls()
        CViewer.ResetControls(Me.Controls)
        'Init obj
        _objCurrDemDet = New tblDemDet
        _objCurrDemDet.IsActive = True

        'txtDemDet.Text = ""
    End Sub

    Public Sub GetInfoByForm()
        With _objCurrDemDet
            .DemDetName = txtDemDet.Text
            '.IsActive = chkIsActive.Checked
        End With
    End Sub

    Private Sub gridViewDemDet_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gridView.CurrentCellChanged
        'Load info
        Try
            If _ucCommands Is Nothing Then
                Return
            End If

            If gridView.CurrentRow Is Nothing Then
                Return
            End If

            'Kiểm tra nếu đang cập nhật/thêm mới thì không hiển thị dữ liệu
            If _ucCommands.btnUpdate.Enabled Then
                Return
            End If

            Dim id As Integer = gridView.CurrentRow.Cells("ID_DemDet").Value
            _objCurrDemDet = _objDemDetController.SelectRecordById(id)
            '_CurrIndex = gridViewDemDet.CurrentRow.Index

            'Fill company's fields
            LoadForm()
        Catch ex As Exception

        End Try
    End Sub

#Region "Commands"
    ''' <summary>
    ''' Init commands
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub InitCommands()
        Dim controlCollect As New List(Of Control)
        controlCollect.Add(BarSearch)
        '_ucCommands = New ucCommands(Me, controlCollect)
        _ucCommands.InitControl(Me, controlCollect)
        _ucCommands.ShowHideButtons(True, True, True)
        _ucCommands.btnAddEvent_Click = New EventHandler(AddressOf btnAdd_Click)
        _ucCommands.btnEditEvent_Click = New EventHandler(AddressOf btnEdit_Click)
        _ucCommands.btnDeleteEvent_Click = New EventHandler(AddressOf btnDel_Click)
        _ucCommands.btnUpdateEvent_Click = New EventHandler(AddressOf btnUpdate_Click)
        _ucCommands.btnCancelEvent_Click = New EventHandler(AddressOf btnCancel_Click)
        _ucCommands.Dock = DockStyle.Fill
        PanelExCommand.Controls.Add(_ucCommands)
    End Sub

    Public Sub FocusControl()
        txtDemDet.Focus()
        txtDemDet.SelectionLength = 0
    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'EnableButtons(True)
        ResetControls()
        FocusControl()
    End Sub

    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        FocusControl()
        'EnableButtons(True)
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If MessageBox.Show("Delete this record?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
            Try
                Dim indexRow As Integer = gridView.CurrentRow.Index
                _objCurrDemDet.IsActive = False
                _objDemDetController.Update(_objCurrDemDet)

                'Xóa row tại indexRow và focus sau khi xóa
                gridView.Rows.RemoveAt(indexRow)
                indexRow -= 1
                If indexRow >= 0 Then
                    For Each col As DataGridViewColumn In gridView.Columns
                        If col.Visible Then
                            gridView.CurrentCell = gridView.Rows(indexRow).Cells(col.Index)
                            Exit For
                        End If
                    Next
                End If

                'Write log
                Dim objLogController As New LogController
                objLogController.Insert(enumAction.Delete, String.Format("Dem/Det Name {0}", _objCurrDemDet.DemDetName))

                'BindDataGridView(indexRow)
                'gridViewDemDet.Rows.Remove(gridViewDemDet.CurrentRow)
                'If gridViewDemDet.Rows.Count = 0 Then
                '    ResetControls()
                'End If
            Catch ex As Exception
#If DEBUG Then
                Throw ex
#Else
                MessageBox.Show(ex.Message)
#End If
            End Try

        End If
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            GetInfoByForm()

            Dim action As enumAction
            'Dim indexRow As Integer = -1
            If _objCurrDemDet.ID_DemDet > 0 Then
                _objDemDetController.Update(_objCurrDemDet)
                action = enumAction.Edit
                'indexRow = gridView.CurrentRow.Index
            Else
                _objDemDetController.Insert(_objCurrDemDet)
                action = enumAction.Add
                'indexRow = gridView.Rows.Count
            End If
            'Write log
            Dim objLogController As New LogController
            objLogController.Insert(action, String.Format("Dem/Det ({0})", _objCurrDemDet.DemDetName))
            'Refresh gridview
            BindDataGridView("ID_DemDet", _objCurrDemDet.ID_DemDet)
            'BindDataGridView(indexRow)
        Catch ex As Exception
#If DEBUG Then
            Throw ex
#Else
            MessageBox.Show(ex.Message)
#End If
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'EnableButtons(False)
        gridViewDemDet_CurrentCellChanged(Nothing, Nothing)
    End Sub
#End Region

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        BindDataGridView(-1)
    End Sub

    Private Sub btnCancelSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelSearch.Click
        txtNameSearch.Text = ""
        Me.btnSearch.PerformClick()
    End Sub
End Class
